using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace cs2335.lab5
{
    public class ComboBox: IComponent
    {

        #region Variables
        protected Rectangle container = new Rectangle(0, 0, 100, 50);
        protected StringFormat labelFormat = new StringFormat(StringFormatFlags.NoWrap);
        protected SolidBrush backColor = new SolidBrush(Color.FloralWhite);
        protected Font font = new Font("SansSerif", 10);
        protected CCTForm owner;
        protected bool hasFocus = false;
        protected bool hidden = false;
        protected string name;
        protected string text;

        protected List<string> items;
        protected int buttonWidth;
        protected List<int> indices;
        protected int topIndex;
        protected int visibleRange;
        protected Rectangle up;
        protected Rectangle down;
        protected Rectangle scroll;
        protected Point[] upPoints;
        protected Point[] downPoints;
        protected int lineHeight;
        protected Rectangle expand;
        protected Rectangle textBox;
        protected Point[] expandPoints;
        protected Rectangle top;
        protected bool multiselect = false;
        protected bool expanded = false;
        protected int visIndex;
        #endregion

        #region Properties
        /// <summary>
        /// Tells whether or not a component is hidden. If it is hidden,
        /// it should not be receiving actions.
        /// </summary>
        public bool Hidden
        {
            get { return hidden; }
        }

        /// <summary>
        /// Stores the width and height of the component
        /// </summary>
        public Size Size
        {
            get { return container.Size; }
            set { container.Size = value; Invalidate(); }
        }

        public Point Location
        {
            get { return container.Location; }
            set
            {
                container.Location = value;
                SetSubComponents();
                Invalidate();
            }
        }

        public Rectangle Bounds
        {
            get { return container; }
            set
            {
                container = value;
                SetSubComponents();
                Invalidate();
            }
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public System.Drawing.Font Font
        {
            get { return font; }
            set { font = value; Invalidate(); }
        }

        public string Text
        {
            get { return text; }
            set { text = value; Invalidate(); }
        }

        public CCTForm Owner
        {
            get { return owner; }
            set { owner = value; }
        }

        public Color BackColor
        {
            get { return backColor.Color; }
            set { backColor.Color = value; Invalidate(); }
        }
        #endregion

        #region Events
        public event EventHandler Click;
        public event EventHandler GotFocus;
        public event EventHandler KeyPress;
        public event EventHandler KeyDown;
        public event EventHandler LostFocus;
        public event EventHandler Paint;
        #endregion

        #region IComponent Members
        public void Invalidate()
        {
            if (owner != null)
            {
                owner.Invalidate();
            }
        }

        public void Hide()
        {
            hidden = true;
            Invalidate();
        }

        public void Show()
        {
            hidden = false;
            Invalidate();
        }

        public void OnPaint(PaintEventArgs e)
        {
            if (!hidden)
            {
                Graphics g = e.Graphics;
                g.FillRectangle(backColor, top);
                DrawFirstItem(g);
                g.FillRectangle(new SolidBrush(Color.PaleGoldenrod), expand);
                Draw3DBorder(g, expand);
                DrawExpandArrow(g);
                Draw3DBorder(g, top);

                if (expanded)
                {
                    g.FillRectangle(new SolidBrush(Color.FloralWhite), textBox);
                    Draw3DBorder(g, textBox);
                    g.FillRectangle(new SolidBrush(Color.PaleGoldenrod), up);
                    Draw3DBorder(g, up);
                    g.FillRectangle(new SolidBrush(Color.PaleGoldenrod), down);
                    Draw3DBorder(g, down);
                    g.FillRectangle(new SolidBrush(Color.Khaki), scroll);

                    DrawVisibleItems(g);
                    DrawArrows(g);

                    DrawFocusBorder(g);
                }

                if (Paint != null)
                {
                    Paint(this, e);
                }
            }

        }

        public void OnGotFocus(EventArgs e)
        {
            hasFocus = true;
            if (GotFocus != null)
            {
                GotFocus(this, e);
            }
            owner.Invalidate();
        }

        public void OnLostFocus(EventArgs e)
        {
            hasFocus = false;
            if (LostFocus != null)
            {
                LostFocus(this, e);
            }
            owner.Invalidate();
        }

        public void OnMouseClick(System.Windows.Forms.MouseEventArgs e)
        {
            if (expand.Contains(e.Location))
            {
                expanded = !expanded;
                Invalidate();
            }
            if (expanded)
            {
                if (up.Contains(e.Location))
                {
                    if (items.Count > visibleRange)
                    {
                        if (topIndex > 0)
                        {
                            topIndex--;
                            Invalidate();
                        }
                    }
                }
                else if (down.Contains(e.Location))
                {
                    if (items.Count > visibleRange)
                    {
                        if (topIndex + visibleRange - 1 < items.Count - 1)
                        {
                            topIndex++;
                            Invalidate();
                        }
                    }
                }
                else if (textBox.Contains(e.Location) && !scroll.Contains(e.Location))
                {
                    int index = (int)(e.Location.Y - textBox.Y) / (lineHeight);
                    index += topIndex;
                    if (multiselect)
                    {
                        if (indices.Contains(index))
                        {
                            indices.Remove(index);
                            Invalidate();
                        }
                        else if (items.Count > index)
                        {
                            indices.Add(index);
                            visIndex = index;
                            Invalidate();
                        }
                    }
                    else
                    {
                        indices.Clear();
                        indices.Add(index);
                        visIndex = index;
                        /// dprather
                        /// added to make the combobox hide once clicked
                        /// in singleselect mode
                        expanded = false;
                        text = items[visIndex];
                        Invalidate();
                    }
                }
            }
        }

        public void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
        {
            /* ignore */
        }

        public void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
        {
            /* ignore */
        }

        public void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            /* ignore */
        }

        public void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
        {
            //Invokes a Click event if the user hits ENTER
            //  while this component has focus
            if (e.KeyChar == '\r')
            {
                if (Click != null)
                {
                    Click(this, e);
                }
            }

            if (KeyPress != null)
            {
                KeyPress(this, e);
            }
        }

        public void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            if (KeyDown != null)
            {
                KeyDown(this, e);
            }
        }
        #endregion

        public List<string> Items
        {
            get
            {
                return items;
            }
            set
            {
                items = value;
            }
        }

        public List<int> Selected
        {
            get { return indices; }
            set { indices = value; }
        }

        public int ButtonWidth
        {
            get { return buttonWidth; }
            set { buttonWidth = value + (int)Pens.White.Width; }
        }

        public bool MultiSelect
        {
            get { return multiselect; }
            set { multiselect = value; }
        }

        public ComboBox()
        {
            items = new List<string>();
            indices = new List<int>();
            buttonWidth = 15 + (int)Pens.White.Width;

            topIndex = 0;
            lineHeight = (int)(font.Size * 1.5);

            upPoints = new Point[3];
            downPoints = new Point[3];
            expandPoints = new Point[3];

            SetSubComponents();
        }

        private void SetSubComponents()
        {
            top = new Rectangle(container.Left, container.Top, container.Width, 25);
            expand = new Rectangle(top.Right - buttonWidth, top.Top,
                buttonWidth, top.Height);
            textBox = new Rectangle(container.Left, top.Bottom, container.Width, container.Height - top.Height);
            up = new Rectangle(textBox.Right - buttonWidth, textBox.Top,
                buttonWidth, buttonWidth);
            down = new Rectangle(textBox.Right - buttonWidth, textBox.Bottom - buttonWidth,
                buttonWidth, buttonWidth);
            scroll = new Rectangle(textBox.Right - buttonWidth, up.Bottom,
                buttonWidth, up.Bottom - down.Top);

            visibleRange = (int)(textBox.Height / lineHeight);

            CreateArrows();
            CreateExpandArrow();
        }

        private void DrawArrows(Graphics g)
        {
            Pen pen = new Pen(Brushes.DarkGoldenrod);
            g.DrawLine(pen, upPoints[0], upPoints[1]);
            g.DrawLine(pen, upPoints[1], upPoints[2]);

            g.DrawLine(pen, downPoints[0], downPoints[1]);
            g.DrawLine(pen, downPoints[1], downPoints[2]);
        }

        private void DrawExpandArrow(Graphics g)
        {
            Pen pen = new Pen(Brushes.DarkGoldenrod);
            g.DrawLine(pen, expandPoints[0], expandPoints[1]);
            g.DrawLine(pen, expandPoints[1], expandPoints[2]);
        }

        private void CreateArrows()
        {
            int sideMargin = 5;
            int vertMargin = 5;

            upPoints[0] = new Point(up.Left + sideMargin, up.Bottom - vertMargin);
            upPoints[1] = new Point(up.Left + up.Width / 2, up.Top + vertMargin);
            upPoints[2] = new Point(up.Right - sideMargin, up.Bottom - vertMargin);

            downPoints[0] = new Point(down.Left + sideMargin, down.Top + vertMargin);
            downPoints[1] = new Point(down.Left + down.Width / 2, down.Bottom - vertMargin);
            downPoints[2] = new Point(down.Right - sideMargin, down.Top + vertMargin);
        }

        private void CreateExpandArrow()
        {
            int sideMargin = 5;
            int vertMargin = 5;

            expandPoints[0] = new Point(expand.Left + sideMargin, expand.Top + vertMargin);
            expandPoints[1] = new Point(expand.Left + down.Width / 2, expand.Bottom - vertMargin);
            expandPoints[2] = new Point(expand.Right - sideMargin, expand.Top + vertMargin);
        }

        private void DrawFocusBorder(Graphics g)
        {
            int PenWidth = (int)Pens.White.Width;

            g.DrawLine(Pens.DarkGoldenrod, new Point(container.Left, container.Top),
                new Point(container.Right - PenWidth, container.Top));
            g.DrawLine(Pens.DarkGoldenrod, new Point(container.Left, container.Top),
                new Point(container.Left, container.Bottom));
            g.DrawLine(Pens.PaleGoldenrod, new Point(container.Left, container.Bottom),
                new Point(container.Right - PenWidth, container.Bottom));
            g.DrawLine(Pens.PaleGoldenrod, new Point(container.Right - PenWidth, container.Bottom),
                new Point(container.Right - PenWidth, container.Top));
        }

        private void Draw3DBorder(Graphics g, Rectangle r)
        {
            int PenWidth = (int)Pens.White.Width;

            g.DrawLine(Pens.PaleGoldenrod, new Point(r.Left, r.Top),
                new Point(r.Right - PenWidth, r.Top));
            g.DrawLine(Pens.PaleGoldenrod, new Point(r.Left, container.Top),
                new Point(r.Left, r.Bottom));
            g.DrawLine(Pens.DarkGoldenrod, new Point(r.Left, r.Bottom),
                new Point(r.Right - PenWidth, r.Bottom));
            g.DrawLine(Pens.DarkGoldenrod, new Point(container.Right - PenWidth, r.Bottom),
                new Point(r.Right - PenWidth, r.Top));
        }

        private void DrawVisibleItems(Graphics g)
        {
            float fontY = textBox.Y + 3;
            float xMargin = 5;
            int lineCount = 0;

            Rectangle selection = new Rectangle(container.X + (int)Pens.PaleGoldenrod.Width,
                textBox.Y + (int)Pens.PaleGoldenrod.Width, container.Width - buttonWidth, 
                lineHeight);

            int endIndex = topIndex + visibleRange;
            if (endIndex > items.Count - 1)
            {
                for (int i = topIndex; i < items.Count; i++)
                {
                    if (indices.Contains(i))
                    {
                        selection.Y = (int)(fontY + lineHeight * lineCount);
                        g.FillRectangle(new SolidBrush(Color.Khaki), selection);
                    }
                    g.DrawString(items[i], font, Brushes.Black,
                        new PointF(container.X + xMargin, fontY + (lineHeight * lineCount++)));
                }
            }else {
                for (int i = topIndex; i < endIndex; i++)
                {
                    if (indices.Contains(i))
                    {
                        selection.Y = (int)(fontY + lineHeight * lineCount);
                        g.FillRectangle(new SolidBrush(Color.Khaki), selection);
                    }
                    g.DrawString(items[i], font, Brushes.Black,
                        new PointF(container.X + xMargin, fontY + (lineHeight * lineCount++)));
                }
            }
        }

        private void DrawFirstItem(Graphics g)
        {
            float fontY = container.Y + font.Size / 2;
            float xMargin = 5;

            if (indices.Count > 0)
            {
                try
                {
                    g.DrawString(items[visIndex], font, Brushes.Black, new PointF(container.X + xMargin, fontY));
                }
                catch (ArgumentOutOfRangeException)
                {
                    /// ignore drawing if the user is clicking
                    /// outside of the drop-down list
                }
            }
            else
            {
                g.DrawString(items[0], font, Brushes.Black, new PointF(container.X + xMargin, fontY));
            }
        }
    }
}
